package iss;

import iss.list.MyList;
import iss.list.Node;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by us on 2016/10/6.
 */
public class Main_B {
    public static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException{

        MyList list = new MyList();
        list.insert(list.getHead(), 5);
        list.insert(list.getHead(), 4);
        list.insert(list.getHead(), 3);
        list.insert(list.getHead(), 2);
        list.insert(list.getHead(), 1);

        System.out.println("before -- size:"+list.getSize());

        // TODO: Implement a multithreaded test case against requirement A.
       Thread ta = new Thread(){
            @Override
            public void run(){
                lock.lock();
                for (Node n = list.getHead().getNext(); n!=list.getTail(); n=n.getNext()){

                    try{
                        list.insert(list.getHead().getNext(), 1);

                    }
                    finally{
                        lock.unlock();
                    }

                 //   System.out.printf("%d ",n.getData());
                }

            }

        };
        System.out.println();
       Thread tb = new Thread() {
            @Override
            public void run() {
               lock.lock();
                for (Node n = list.getHead().getNext(); n!=list.getTail(); n=n.getNext()){

                   try {
                        list.remove(list.getHead().getNext().getNext());
                    }
                    finally {
                        lock.unlock();
                    }
                  //  System.out.printf("%d ", n.getData());
                }

            }
        };

        System.out.println("after -- size:"+list.getSize());
        ta.start();
        tb.start();
        Thread.sleep(10000);

        // Traverse from head to tail, exclude head and tail
        System.out.println("遍历检查:");
      for (Node n = list.getHead().getNext(); n != list.getTail(); n = n.getNext()) {

            System.out.printf("%d ", n.getData());
        }
        System.out.println();



        // Traverse from tail to head, exclude tail and head.
        for (Node n = list.getTail().getPrev(); n!=list.getHead(); n=n.getPrev()) {
            System.out.printf("%d ", n.getData());
        }
        System.out.println();
    }
}

